package com.msec.permission.demo;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class ActivityLifeCycleHandler implements Application.ActivityLifecycleCallbacks {

    private static final String TAG = "permission_demo_logger";
    public static ArrayList<PermissionRequest> permissionRequestList;     // 权限状态声明
    public ArrayList<WeakReference<Activity>> activities;
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == ActivityActionType.REQUEST_PERMISSION) {
                Activity activity = (Activity) msg.obj;
                requestPermissionWhenActivityResume(activity);
            }
        }
    };

    private static void requestPermissionWhenActivityResume(Activity activity) {

        /**
         * （3）UI未初始化完成时请求
         * */
        for (int i = 0; i < permissionRequestList.size(); i++) {
            PermissionRequest permissionRequest = permissionRequestList.get(i);
            if(permissionRequest.getStatus() == PermissionAccessStatus.DENIED) {
                RequestHelper.requestPermission(activity, permissionRequest);
            }
        }
    }

    public static ActivityLifeCycleHandler instance;

    public ActivityLifeCycleHandler() {
        this.activities = new ArrayList<>();
        this.permissionRequestList = new ArrayList<>();
    }

    public static ActivityLifeCycleHandler INSTANCE() {
        if (instance == null) {
            synchronized (ActivityLifeCycleHandler.class) {
                if (instance == null) {
                    instance = new ActivityLifeCycleHandler();
                }
            }
        }
        return instance;
    }

    public void register(Application application) {
        try {
            application.registerActivityLifecycleCallbacks(this);
        } catch (Exception e) {
            // Logger.printStackTrace(msecContext, e);
        }
    }

    public void remove(Application application) {
        try {
            application.unregisterActivityLifecycleCallbacks(this);
        } catch (Exception e) {
            // Logger.printStackTrace(msecContext, e);
        }
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityCreated");
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityStarted");
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityResumed");
        this.activities.add(new WeakReference<>(activity));

        // TODO 申请权限
//        Message message = new Message();
//        message.what = ActivityActionType.REQUEST_PERMISSION;
//        message.obj = activity;
//        handler.sendMessage(message);
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityPaused");

    }

    @Override
    public void onActivityStopped(Activity activity) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityStopped");
        this.activities.remove(activities.size() - 1);

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivitySaveInstanceState");

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.d(TAG, activity.getLocalClassName() + " => onActivityDestroyed");
    }

    /**
     * =============================================================================================
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public Activity currentActivity() {
        if (activities == null || activities.isEmpty()) {
            return null;
        }
        Activity activity = activities.get(activities.size() - 1).get();
        return activity;
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public void finishCurrentActivity() {
        if (activities == null || activities.isEmpty()) {
            return;
        }
        Activity activity = activities.get(activities.size() - 1).get();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activities == null || activities.isEmpty()) {
            return;
        }
        if (activity != null) {
            activities.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (activities == null || activities.isEmpty()) {
            return;
        }
        for (WeakReference<Activity> weakReference : activities) {
            Activity activity = weakReference.get();
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 按照指定类名找到activity
     *
     * @param cls
     * @return
     */
    public Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (activities != null) {
            for (WeakReference<Activity> weakReference : activities) {
                Activity activity = weakReference.get();
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (activities) {
            final int size = activities.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = activities.get(size).get();
        }
        return mBaseActivity;

    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    public String getTopActivityName() {
        Activity topActivity = null;
        synchronized (activities) {
            final int size = activities.size() - 1;
            if (size < 0) {
                return null;
            }
            topActivity = activities.get(size).get();
        }
        return topActivity.getClass().getName();
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (activities == null) {
            return;
        }
        for (WeakReference<Activity> weakReference : activities) {
            Activity activity = weakReference.get();
            activity.finish();
        }
        activities.clear();
    }

    /**
     * 退出应用程序
     */
    public void appExit() {
        finishAllActivity();
    }
}
